import MyComponent from "../classes/MyComponent.js";
import {generateElement} from "../functions/common.js";

export class MyConsole extends MyComponent{
    constructor(labelText) {
        super();
        this.elem = generateElement({
            type: "div",
            border: "1px solid grey",
            width: "300px",
            backgroundColor: "#393D49",
            color: "white",
        });
        this.elem.innerHTML = "<div id=\"myConsoleShowingArea\" style=\"overflow-y: scroll\" class='none-scroll-bar'></div>\n" +
            "            <form action=\"\" id=\"myConsoleForm\" style=\"border-top: 1px solid white; height: 30px; line-height: 28px;\">\n" +
            "                <label id=\"myConsoleLabel\" style=\"background-color: #393D49; border: none; display: inline; margin-left: 5px\"></label>\n" +
            "                <input type=\"text\" name=\"title\" id=\"myConsoleInput\" style=\"background-color: #393D49; color: white; border: none;display: inline-block\">\n" +
            "            </form>";
        this.labelText = labelText? labelText : "Louis > ";
    }

    init(callBack) {
        this.myConsoleForm = document.getElementById("myConsoleForm");
        this.myConsoleInput = document.getElementById("myConsoleInput");
        this.myConsoleShowingArea = document.getElementById("myConsoleShowingArea");
        this.myConsoleLabel = document.getElementById("myConsoleLabel");
        this.setLabelText(this.labelText);
        this.myConsoleShowingArea.style.height = "200px";
        this.myConsoleInput.autocomplete = "off";
        this.myConsoleForm.onsubmit = (value) => {
            let inputValue = this.myConsoleInput.value;
            if (inputValue && inputValue !== ""){
                try {
                    this.appendText(this.labelText + inputValue);
                    this.myConsoleForm.reset();
                    this.myConsoleShowingArea.scrollTop = this.myConsoleShowingArea.scrollHeight;
                    if (callBack){
                        callBack(inputValue)
                    }
                }catch (e) {
                    console.error("Error", e)
                }
            }
            return false;
        };
    };

    setLabelText(newLabelText){
        this.myConsoleLabel.innerText = newLabelText;
        this.labelText = newLabelText;
    }

    appendText(value){
        this.myConsoleShowingArea.appendChild(generateElement({
            type: "p",
            innerText: value,
            margin: "5px 0"
        }));
    }
}
